﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Chemistry.Models;
using OPCAutomation;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;


namespace Chemistry.WorkFlow
{
    /// <summary>
    /// 氨基化工艺流程 - 可以调节大小的阀门
    /// </summary>
    public class Amination : FlowBaseAll
    {
        #region  字段

        private const int DEFAULT_TEMPERATURE = 22;
        private int _sleepfast = 500;
        private int _reactionSecond = 30;//反正时间
        private static int _reply_command = 0;
        int open = 1;
        int close = 0;
        static bool _isgetoverstate1 = false;
        static bool _isgetoverstate2 = false;
        static bool _isgetoverstate3 = false;
        // 组态数据
        static double _flow_benzene_value ; //间二甲苯流量
        static double _flow_ammonia_value ;  //氨气流量
        static double _flow_oxygen_value ;  //空气流量
        static double _pressure_ammonia_value ;//氨气压力
        static double _temprature_electric_value = DEFAULT_TEMPERATURE;  // 电加热器中温度
        static double _temperature1_value = DEFAULT_TEMPERATURE; //浓1处温度
        static double _temperature2_value = DEFAULT_TEMPERATURE;//浓2处温度
        static double _rate_ammoniaBenzene_value ;//氨气与间二甲苯比例
        static double _rate_gasBenzene_value ;   //空气与间二甲苯比例
        


        //增减量
        static double _flow_benzene_increament;
        static double _flow_benzene_decreament;
        static double _flow_ammonia_increment;
        static double _flow_ammonia_decreament;
        static double _flow_oxygen_increment;
        static double _flow_oxygen_decrement;
        static double _pressure_ammonia_increment ;
        static double _pressure_ammonia_decrement ;
        static double _temperature1_increment ;
        static double _temperature1_decrement;
        static double _temperature2_increment;
        static double _temperature2_decrement;
        static double _rate_ammoniaBenzene_crement = 0.1;
        static double _rate2_gasBenzene_crement = 0.1;

        //配置文件命令
        string _recv = string.Empty;
        string _prefix1 = string.Empty;
        string _prefix2 = string.Empty;
        private string _llcmd;
        private string _ylcmd;
        private string _aicmd;
        string _relaycmd;
        int _warning1number;
        int _warning2number;
        int _fognumber;
        int _stirnumber;
        private Tools.Tool.FlowCommand _flowcommand;


        #endregion

        #region 组态开关状态
        static bool ValveBen_State = false; //间二甲苯进料阀门
        static bool ValveBenBottom_State = false; //间二甲苯流量计下
        static bool ValveBenTop_State = false;    //间二甲苯流量计上
        static bool ValveAmmoniaBenzene_State = false;  //间二甲苯流入流化床反应器阀门
        /// <summary>
        /// 氨气进料阀门
        /// </summary>
        static bool ValveInAmmonia_State = false;
        /// <summary>
        /// 氨气放料阀门
        /// </summary>
        static bool ValveAmmoniaBufTank_State = false;  //进入氨气缓冲罐阀门
        static bool ValveAmmoniaBottom_State = false;  //从氨气缓冲罐 流量计下
        static bool ValveAmmoniaTop_State = false;    //进入氨气 流量计上
        /// <summary>
        /// 空气进料阀门
        /// </summary>
        static bool ValveInO2_State = false;  //空气进料阀门
        /// <summary>
        /// 空气放料阀门
        /// </summary>
        static bool ValveO2AirHeater_State = false;  //空气放入空气加热器阀门   
        static bool ValveO2Reactor_State = false;   //空气经空气加热器流入流化床反应器阀门
        static bool ValveInEleHeater_State = false; //空气放入电加热器阀门
        static bool ValveOutEleHeater_State = false; //空气流出电加热器流向流化床反应器阀门
        /// <summary>
        /// 进油阀门
        /// </summary>
        static bool ValveInOil_State = false;   //外循环进油阀门
        /// <summary>
        /// 回油阀门
        /// </summary>
        static bool ValveOutOil_State = false;//回油阀门
        static bool ValveOilRight_State = false; //流入间二甲苯汽化器阀门
        static bool ValveOilLeft_State = false;  //流入氨气化器阀门
        static bool ValveOutAirHeater_State = false;  //从空气加热器流出阀门
        /// <summary>
        /// 循环水上水阀门
        /// </summary>
        static bool ValveInCold_State = false; //进入放箱冷却水进水阀
        /// <summary>
        /// 循环回水阀门
        /// </summary>
        static bool ValveOutCold_State = false; //进入放箱冷却水回水阀门
        /// <summary>
        /// 导热油循环泵状态
        /// </summary>
        static bool ValveOilPump_State = false;
        /// <summary>
        /// 热水泵状态
        /// </summary>
        static bool ValveHotPump_State = false;
        /// <summary>
        /// 软水阀门
        /// </summary>
        static bool ValveInHotPump_State = false;  //软水进入热水泵阀门
        static bool ValveColdBottom_State = false;  //软水经流量计下部阀门
        static bool ValveColdTop_State = false;  //软水经流量计上部阀门
        static bool ValveH2ORec_State = false;  //软水进入流化床反应器阀门
        /// <summary>
        /// 甲阀状态
        /// </summary>
        static bool ValveGate1_State = false;  //进入放箱的甲阀1
        static bool ValveGate2_State = false;  //进入放箱的甲阀2
        /// <summary>
        /// 紧急切断阀
        /// </summary>
        static bool ValveCutOff_State = false;

        private int _inputBenState = 0;
        private int _inputAmmoniaState = 0;
        private bool _valveFanState = false;
        private bool _valveElectricHeaterState = false;
        private bool _valveInWaterState = false;
        private bool _valveStopState;
        #endregion

        #region OPCItem
        //阀门
        OPCItem ValveBenzene_item;
        OPCItem ValveBenzeneBottom_item;
        OPCItem ValveBenzeneTop_item;
        OPCItem ValveAmmoniaBenzene_item;
        OPCItem ValveInAmmonia_item;
        OPCItem ValveAmmoniaBufTank_item;
        OPCItem ValveAmmoniaBottom_item;
        OPCItem ValveAmmoniaTop_item;
        OPCItem ValveInO2_item;
        OPCItem ValveO2AirHeater_item;
        OPCItem ValveO2Reactor_item;
        OPCItem ValveInEleHeater_item;
        OPCItem ValveOutEleHeater_Item;
        OPCItem ValveInOil_item;
        OPCItem ValveOilRight_item;
        OPCItem ValveOilLeft_item;
        OPCItem ValveOutAirHeater_item;
        OPCItem ValveInCold_item;
        OPCItem ValveOutOil_item;
        OPCItem ValveOutCold_item;
        OPCItem ValveOilPump_item;
        OPCItem ValveHotPump_item;
        OPCItem ValveInHotPump_item;
        OPCItem ValveColdBottom_item;
        OPCItem ValveColdTop_item;
        OPCItem ValveH2ORec_item;
        OPCItem ValveGate1_item;
        OPCItem ValveGate2_item;
        OPCItem ValveCutOff_item;
        OPCItem ValveFan_item;
        OPCItem ValveElectricHeater_item;
        OPCItem ValveInWater_item;
        //管道
        OPCItem FlowInCold_item;
        OPCItem FlowOutCold_item;
        OPCItem FlowOutHot_item;
        OPCItem FlowInSoftWater_item;
        OPCItem FlowOutOil_item;
        OPCItem FlowInBen_item;
        OPCItem FlowOutAmmoniaBen_item;
        OPCItem FlowInAmmonia_item;
        OPCItem FlowOutAmmonia_item;
        OPCItem FlowInO2_item;
        OPCItem FlowOutO2_item;
        OPCItem FlowOilInnerLoop_item;
        OPCItem FlowOilC8H10Ht_item;
        OPCItem FlowOutAirHt_item;
        OPCItem FlowO2Rec_item;
        OPCItem FlowOutElcHt_item;
        OPCItem FlowInElcHt_item;
        OPCItem FlowOutCold1_item;
        OPCItem FlowPumpOli_item;
        OPCItem FlowInBox_item;

        //标签
        OPCItem LabelFlowBenlene_item;
        OPCItem LabelFlowAmmonia_item;
        OPCItem LabelFlowO2_item;
        OPCItem LabelAmmoniaPressure_item;
        OPCItem LabelEletricTemperature_item;
        OPCItem LabelTemperature1_item;
        OPCItem LabelTemperature2_item;
        OPCItem LabelAmmoniaBenRateRate_item;
        OPCItem LabelGasBenRate_item;

        OPCItem LabelTempNH3_item;
        OPCItem LabelTempOil_item;
       
  
        //闪烁
        private OPCItem FlashAmmoniaFlow_item;
        private OPCItem FlashBenFlow_item;
        private OPCItem FlashAmmoniaPressure_item;
        private OPCItem FlashGasFlow_item;
        private OPCItem FlashAmmoniaBenRate_item;
        private OPCItem FlashGasBenRate_item;
        private OPCItem FlashTemperature1_item;
        private OPCItem FlashTemperature2_item;
        private OPCItem FlashEletricTemperature_item;
        private OPCItem FlashWarning_item;

        //可调节的阀门
        private OPCItem InputBen_item;
        private OPCItem InputAmmonia_item;
        #endregion

        #region 初始化
        public Amination(OPCServer opcserver, SerialPort port, bool isinner)
        {
            _opcServer = opcserver;
            _serialPort = port;
            Isinner = isinner;

            InitFiled();
            InitOPC();
            InitOPCItem();
            InitSignal();
        }

        private async Task InitServerData()
        {
            _details = await GetDetailList(GetType().Name);
        }
        private void InitFiled()
        {
            _flow_benzene_value=1; //间二甲苯流量
            _flow_ammonia_value=1;  //氨气流量
            _flow_oxygen_value=1;  //空气流量
            _pressure_ammonia_value=0.01;//氨气压力
            _temprature_electric_value = 22;  // 电加热器中温度
            _temperature1_value = 22; //浓1处温度
            _temperature2_value = 22;//浓2处温度
            _rate_ammoniaBenzene_value=1;//氨气与间二甲苯比例
            _rate_gasBenzene_value=1;   //空气与间二甲苯比例


            _flow_benzene_increament =10;
            _flow_benzene_decreament =10;
            _flow_ammonia_decreament = 10;//氨气减量
            _flow_oxygen_decrement = 5;
            _pressure_ammonia_increment=0.02;
            _pressure_ammonia_decrement=0.02;
            _temperature1_increment=10;
            _temperature1_decrement=10;
            _temperature2_increment=10;
            _temperature2_decrement=10;
            _rate_ammoniaBenzene_crement = 0.1;
            _rate2_gasBenzene_crement = 0.1;
        }
        private void InitSignal()
        {
            if (Isinner)
            {
                ListenSignal();
                open = 1;
                close = 0;

            }
            else
            {
                InitFlowCommandData();
                _serialPort.DataReceived += _serialPort_DataReceived;
                InitOpcItemWithSerialPort();
                ListenSerialPortAndAbnormalData();
                open = 48;
                close = 49;
            }
        }

        #region 外操初始化
        private void InitFlowCommandData()
        {

        }

        private void InitOpcItemWithSerialPort()
        {

        }

        private void ListenSerialPortAndAbnormalData()
        {

        } 
        #endregion
        private void InitOPCItem()
        {
            //阀门
            ValveBenzene_item = GetItem(FiledName.ValveC8H10); 
            ValveBenzene_item.Close();
            ValveBenzeneBottom_item = GetItem(FiledName.ValveC8H10Bottom);
            ValveBenzeneBottom_item.Open();//常开
            ValveBenzeneTop_item = GetItem(FiledName.ValveC8H10Top);
            ValveBenzeneTop_item.Open();//常开

            ValveAmmoniaBenzene_item = GetItem(FiledName.ValveAmmoniaBenzene); ValveAmmoniaBenzene_item.Close();
            ValveInAmmonia_item = GetItem(FiledName.ValveInNH3); ValveInAmmonia_item.Close();
            ValveAmmoniaBufTank_item = GetItem(FiledName.ValveNH3BufTank); ValveAmmoniaBufTank_item.Close();
            ValveAmmoniaBottom_item = GetItem(FiledName.ValveNH3Bottom);
            ValveAmmoniaBottom_item.Open();
            ValveAmmoniaTop_item = GetItem(FiledName.ValveNH3Top);
            ValveAmmoniaTop_item.Open();

            ValveInO2_item = GetItem(FiledName.ValveInO2); ValveInO2_item.Open();
            ValveO2AirHeater_item = GetItem(FiledName.ValveO2AirHeater); 
            ValveO2AirHeater_item.Open();
            ValveO2Reactor_item = GetItem(FiledName.ValveO2Reactor); ValveO2Reactor_item.Close();
            ValveInEleHeater_item = GetItem(FiledName.ValveInEleHeater); ValveInEleHeater_item.Close();
            ValveOutEleHeater_Item = GetItem(FiledName.ValveOutEleHeater); ValveOutEleHeater_Item.Close();
            ValveInOil_item = GetItem(FiledName.ValveInOil); ValveInOil_item.Close();
            ValveOutOil_item = GetItem(FiledName.ValveOutOil); ValveOutOil_item.Close();
            ValveOilRight_item = GetItem(FiledName.ValveOilRight); ValveOilRight_item.Close();
            ValveOilLeft_item = GetItem(FiledName.ValveOilLeft); ValveOilLeft_item.Close();
            ValveOutAirHeater_item = GetItem(FiledName.ValveOutAirHeater); ValveOutAirHeater_item.Close();
            ValveInCold_item = GetItem(FiledName.ValveInCold); ValveInCold_item.Close();
            ValveOutCold_item = GetItem(FiledName.ValveOutCold); ValveOutCold_item.Close();
            ValveOilPump_item = GetItem(FiledName.ValveOilPump); ValveOilPump_item.Close();
            ValveHotPump_item = GetItem(FiledName.ValveHotPump); ValveHotPump_item.Close();
            ValveColdBottom_item = GetItem(FiledName.ValveColdBottom);
            ValveColdBottom_item.Open();
            ValveColdTop_item = GetItem(FiledName.ValveColdTop);
            ValveColdTop_item.Open();
            ValveH2ORec_item = GetItem(FiledName.ValveH2ORec); ValveH2ORec_item.Close();
            ValveGate1_item = GetItem(FiledName.ValveGate1); ValveGate1_item.Close();
            ValveGate2_item = GetItem(FiledName.ValveGate2); ValveGate2_item.Close();
            ValveCutOff_item = GetItem(FiledName.ValveCutOff); ValveCutOff_item.Open();
            ValveFan_item = GetItem(FiledName.ValveFan);
            ValveFan_item.Close();
            ValveElectricHeater_item = GetItem(FiledName.ValveElectricHeater);
            ValveElectricHeater_item.Close();
            ValveInWater_item = GetItem(FiledName.ValveInWater);
            ValveInWater_item.Close();


            //管道
            FlowInCold_item = GetItem(FiledName.FlowInCold); FlowInCold_item.Close();
            FlowOutCold_item = GetItem(FiledName.FlowOutCold); FlowOutCold_item.Close();
            FlowInSoftWater_item = GetItem(FiledName.FlowInSoftWater); FlowInSoftWater_item.Close();
            FlowOutOil_item = GetItem(FiledName.FlowOutOil); FlowOutOil_item.Close();
            FlowInBen_item = GetItem(FiledName.FlowInC8H10); FlowInBen_item.Close();
            FlowOutAmmoniaBen_item = GetItem(FiledName.FlowOutAmmoniaBen); FlowOutAmmoniaBen_item.Close();
            FlowInAmmonia_item = GetItem(FiledName.FlowInAmmonia); FlowInAmmonia_item.Close();
            FlowOutAmmonia_item = GetItem(FiledName.FlowOutAmmonia);
            FlowOutAirHt_item.Close();
            FlowInO2_item = GetItem(FiledName.FlowInO2); FlowInO2_item.Close();
            FlowOutO2_item = GetItem(FiledName.FlowOutO2); FlowOutO2_item.Close();
            FlowOilInnerLoop_item = GetItem(FiledName.FlowOilInnerLoop); FlowInO2_item.Close();
            FlowOilC8H10Ht_item = GetItem(FiledName.FlowOilC8H10Ht); FlowOilC8H10Ht_item.Close();
            FlowOutAirHt_item = GetItem(FiledName.FlowOutAirHt); FlowOutAirHt_item.Close();
            FlowO2Rec_item = GetItem(FiledName.FlowO2Rec); FlowO2Rec_item.Close();
            FlowOutElcHt_item = GetItem(FiledName.FlowOutElcHt); FlowOutElcHt_item.Close();
            FlowInElcHt_item = GetItem(FiledName.FlowInElcHt);
            FlowInElcHt_item.Close();
            FlowOutCold1_item = GetItem(FiledName.FlowOutCold1); FlowOutCold1_item.Close();
            FlowPumpOli_item = GetItem(FiledName.FlowPumpOil); FlowPumpOli_item.Close();
            FlowInBox_item = GetItem(FiledName.FlowInBox); FlowInBox_item.Close();
            //标签
            LabelFlowBenlene_item = GetItem(FiledName.LabelFlowBenlene); LabelFlowBenlene_item.Write(_flow_benzene_value);
            LabelFlowAmmonia_item = GetItem(FiledName.LabelFlowNH3); LabelFlowAmmonia_item.Write(_flow_ammonia_value);
            LabelFlowO2_item = GetItem(FiledName.LabelFlowO2); LabelFlowO2_item.Write(_flow_oxygen_value);
            LabelAmmoniaPressure_item = GetItem(FiledName.LabelAmmoniaPressure);
            LabelAmmoniaPressure_item.Write(_pressure_ammonia_value);

            LabelEletricTemperature_item = GetItem(FiledName.LabelEletricTemperature); LabelEletricTemperature_item.Write(_temprature_electric_value);
            LabelTemperature1_item = GetItem(FiledName.LabelTemperature1); LabelTemperature1_item.Write(_temperature1_value);
            LabelTemperature2_item = GetItem(FiledName.LabelTemperature2); LabelTemperature2_item.Write(_temperature2_value);
            LabelTempNH3_item = GetItem(FiledName.LabelTempNH3); LabelTempNH3_item.Close();
            LabelAmmoniaBenRateRate_item = GetItem(FiledName.LabelAmmoniaBenRateRate); 
            LabelAmmoniaBenRateRate_item.Write(_rate_ammoniaBenzene_value);
            LabelGasBenRate_item = GetItem(FiledName.LabelGasBenRate); LabelGasBenRate_item.Write(_rate_gasBenzene_value);
            LabelTempOil_item = GetItem(FiledName.LabelTempOil); LabelTempOil_item.Close();
            
            //闪烁
            FlashAmmoniaFlow_item = GetItem(FiledName.FlashAmmoniaFlow);
            FlashAmmoniaBenRate_item.Close();
            FlashBenFlow_item = GetItem(FiledName.FlashBenFlow);
            FlashBenFlow_item.Close();
            FlashAmmoniaPressure_item = GetItem(FiledName.FlashAmmoniaPressure);
            FlashAmmoniaPressure_item.Close();
            FlashGasFlow_item = GetItem(FiledName.FlashGasFlow);
            FlashBenFlow_item.Close();
            FlashAmmoniaBenRate_item = GetItem(FiledName.FlashAmmoniaBenRate);
            FlashBenFlow_item.Close();
            FlashGasBenRate_item = GetItem(FiledName.FlashGasBenRate);
            FlashBenFlow_item.Close();
            FlashTemperature1_item = GetItem(FiledName.FlashTemperature1);
            FlashTemperature1_item.Close();
            FlashTemperature2_item = GetItem(FiledName.FlashTemperature2);
            FlashTemperature2_item.Close();
            FlashEletricTemperature_item = GetItem(FiledName.FlashEletricTemperature);
            FlashEletricTemperature_item.Close();
            FlashWarning_item = GetItem(FiledName.FlashWarning);
            FlashWarning_item.Close();


            InputBen_item = GetItem(FiledName.InputBen);
            InputBen_item.Write(0);
            InputAmmonia_item = GetItem(FiledName.InputAmmonia);
            InputAmmonia_item.Write(0);
            Console.WriteLine("结束 InitOPCItem" + DateTime.Now.ToString("F"));
        }

        private void ListenSignal()
        {
            Console.WriteLine("开始 ListenSignal" +DateTime.Now.ToString("F"));
            Task t = new Task(() =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    ValveBen_State = Convert.ToInt32(ReadItem(FiledName.ValveC8H10)) == open;
                    ValveAmmoniaBenzene_State = Convert.ToInt32(ReadItem(FiledName.ValveAmmoniaBenzene)) == open;
                    ValveInAmmonia_State = Convert.ToInt32(ReadItem(FiledName.ValveInNH3)) == open;
                    ValveAmmoniaBufTank_State = Convert.ToInt32(ReadItem(FiledName.ValveNH3BufTank)) == open;
                    ValveInO2_State = Convert.ToInt32(ReadItem(FiledName.ValveInO2)) == open;
                    ValveO2AirHeater_State = Convert.ToInt32(ReadItem(FiledName.ValveO2AirHeater)) == open;
                    ValveO2Reactor_State = Convert.ToInt32(ReadItem(FiledName.ValveO2Reactor)) == open;
                    ValveInEleHeater_State = Convert.ToInt32(ReadItem(FiledName.ValveInEleHeater)) == open;

                    ValveOutEleHeater_State = Convert.ToInt32(ReadItem(FiledName.ValveOutEleHeater)) == open;
                    ValveInOil_State = Convert.ToInt32(ReadItem(FiledName.ValveInOil)) == open;
                    ValveOutOil_State = Convert.ToInt32(ReadItem(FiledName.ValveOutOil)) == open;
                    ValveOilRight_State = Convert.ToInt32(ReadItem(FiledName.ValveOilRight)) == open;
                    ValveOilLeft_State = Convert.ToInt32(ReadItem(FiledName.ValveOilLeft)) == open;
                    ValveOutAirHeater_State = Convert.ToInt32(ReadItem(FiledName.ValveOutAirHeater) )== open;
                    ValveInCold_State = Convert.ToInt32(ReadItem(FiledName.ValveInCold)) == open;
                    ValveOutCold_State = Convert.ToInt32(ReadItem(FiledName.ValveOutCold)) == open;
                    ValveOilPump_State = Convert.ToInt32(ReadItem(FiledName.ValveOilPump)) == open;
                    ValveHotPump_State = Convert.ToInt32(ReadItem(FiledName.ValveHotPump)) == open;
                    ValveInHotPump_State = Convert.ToInt32(ReadItem(FiledName.ValveInHotPump)) == open;
                    ValveH2ORec_State = Convert.ToInt32(ReadItem(FiledName.ValveH2ORec)) == open;
                    ValveGate1_State = Convert.ToInt32(ReadItem(FiledName.ValveGate1)) == open;
                    ValveGate2_State = Convert.ToInt32(ReadItem(FiledName.ValveGate2)) == open;
                    ValveCutOff_State = Convert.ToInt32(ReadItem(FiledName.ValveCutOff)) == open;

                    _inputAmmoniaState = Convert.ToInt32(ReadItem(FiledName.InputAmmonia));
                    _inputBenState = Convert.ToInt32(ReadItem(FiledName.InputBen));
                    _valveFanState = Convert.ToInt32(ReadItem(FiledName.ValveFan))==open;
                    _valveElectricHeaterState = Convert.ToInt32(ReadItem(FiledName.ValveElectricHeater))==open;
                    _valveInWaterState = Convert.ToInt32(ReadItem(FiledName.ValveInWater)) == open;

                    DateTime dtnow = DateTime.Now;
                    Step step = new Step()
                    {
                        Date = dtnow,
                        Status =
                     {
                         {StatusName.间二甲苯进料阀,_inputBenState},
                         {StatusName.间二甲苯流量,_flow_benzene_value},
                         {StatusName.间二甲苯流入反应器阀门,Convert.ToInt32(ReadItem(FiledName.ValveAmmoniaBenzene))},
                        
                         {StatusName.氨气阀门,_inputAmmoniaState},
                         {StatusName.氨气流量,_flow_ammonia_value},
                         {StatusName.氨气流入缓冲罐阀门,Convert.ToInt32(ReadItem(FiledName.ValveNH3BufTank))},
                         {StatusName.氨缓冲罐压力,_pressure_ammonia_value},

                         {StatusName.空气阀门,Convert.ToInt32(ReadItem(FiledName.ValveInO2))},
                         {StatusName.空气流入反应器阀门,Convert.ToInt32(ReadItem(FiledName.ValveO2Reactor))},
                         {StatusName.空气流量,_flow_oxygen_value},

                         {StatusName.空气流入空气加热器阀门,Convert.ToInt32(ReadItem(FiledName.ValveO2AirHeater))},
                         {StatusName.空气流入电加热器阀门,Convert.ToInt32(ReadItem(FiledName.ValveInEleHeater))},                         
                         {StatusName.空气流出电加热器, Convert.ToInt32(ReadItem(FiledName.ValveOutEleHeater))},
                        
                         {StatusName.经空气加热器出油阀门,Convert.ToInt32(ReadItem(FiledName.ValveOutAirHeater))},
                         {StatusName.冷却水上水阀门,Convert.ToInt32(ReadItem(FiledName.ValveInCold))},
                         {StatusName.冷却水回水阀门,Convert.ToInt32(ReadItem(FiledName.ValveOutCold ))},
                        // {StatusName.热水泵阀门,Convert.ToInt32(ReadItem(FiledName.ValveHotPump))},
                         {StatusName.经热水泵进水阀门,Convert.ToInt32(ReadItem(FiledName.ValveInHotPump))},
                         {StatusName.软水流入反应器阀门,Convert.ToInt32(ReadItem(FiledName.ValveH2ORec))},
                         {StatusName.浓1温度,_temperature1_value},
                        // {StatusName.闸阀1,Convert.ToInt32(ReadItem(FiledName.ValveGate1))},
                         //{StatusName.闸阀2,Convert.ToInt32(ReadItem(FiledName.ValveGate2))},
                         {StatusName.氨气与间二甲苯比例,_rate_ammoniaBenzene_value},
                         {StatusName.空气与间二甲苯比例,_rate_gasBenzene_value},
                          {StatusName.导热油循环泵, Convert.ToInt32(ReadItem(FiledName.ValveOilPump))},
                         //  {StatusName.出油阀门,Convert.ToInt32(ReadItem(FiledName.ValveOutOil))},
                        // {StatusName.外循环进油阀门,Convert.ToInt32(ReadItem(FiledName.ValveInOil))},
                        // {StatusName.左侧出油阀门,Convert.ToInt32(ReadItem(FiledName.ValveOilLeft))},
                         //{StatusName.右侧出油阀门,Convert.ToInt32(ReadItem(FiledName.ValveOilRight))},

                          {StatusName.液氨进料调节阀, _inputAmmoniaState},
                          {StatusName.间二甲苯进料调节阀, _inputBenState},
                          {StatusName.电加热器开关,Convert.ToInt32(ReadItem(FiledName.ValveElectricHeater))},
                          {StatusName.罗茨风机开关,Convert.ToInt32(ReadItem(FiledName.ValveFan))},
                          {StatusName.冷却水进水阀,Convert.ToInt32(ReadItem(FiledName.ValveInWater))}
                     }
                    };
                    if(_isbeginned)
                        _steps.Add(step);
                    Thread.Sleep(500);
                }
            });
            t.Start();

        }

        #endregion

        #region  监听步骤，计分

        string recv = string.Empty;
        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int n = _serialPort.BytesToRead;
            byte[] data = new byte[n];
            _serialPort.Read(data, 0, data.Length);
            string temp = Encoding.Default.GetString(data);
            recv += temp;
            if (recv.Contains("\n"))
            {
                Match macth = Regex.Match(recv, @"\d{5}_\d{3}");
                if (macth.Success)
                {
                    string s = macth.Groups[0].Value.Split('_')[1];
                    int v = Convert.ToInt32(s);
                    string r = Convert.ToString(v, 2).PadLeft(8, '0');
                    string first = macth.Groups[0].Value.Split('_')[0];
                }
            }
        }

       
        #endregion

        #region  处理异常方法

        #region 温度异常
        public override void TemperatureAbnormal()
        {
            _warningDicionary.Add(WarningType.温度异常, false);
            Task.Run(() =>
            {
                while (_temperature1_value < 500)
                {
                    _temperature1_value += 3;
                    LabelTemperature1_item.Write(_temperature1_value);
                    //SpTemperatureValue(_temperature1_value);
                    Thread.Sleep(_sleepfast);
                }
                BeginWarning(WarningType.温度异常);
                FlashTemperature1_item.StartFlow();
                HandleTempretureAbnormal();
            });
        }

        private void HandleTempretureAbnormal()
        {
            Task.Run(
                () =>
                {
                    Parallel.Invoke(CloseHotOil);
                    StopWarning(WarningType.温度异常);
                    _warningDicionary[WarningType.温度异常] = true;
                });
        }

        private void CloseHotOil()
        {
            while (!_listenCts.IsCancellationRequested)//true
            {
                if (_temperature1_value <= 200)
                {
                    AddCompose("处理温度异常：降温完成");
                    break;
                }
                Thread.Sleep(_sleepfast);
            }
        } 
        #endregion

        #region 泄漏
        void BeginLeakAbnormal()
        {
            _isleakAbnormal = false;
            BeginWarning(WarningType.泄漏);
            BeginLeak();
            _warningDicionary.Add(WarningType.泄漏, false);
            HandleLeakAbnormal();
        }

        private void HandleLeakAbnormal()
        {
            //打开急停按钮
            //while (!_listenCts.IsCancellationRequested)//true
            //{
               
            //    if (ValveStop_State)
            //    {
            //        AddCompose("处理泄漏异常：按下急停按钮");
            //        break;
            //    }
            //    Thread.Sleep(_sleepfast);
            //}
            ////关闭蒸汽和异丁烯
            //Parallel.Invoke(() =>
            //{

            //    while (!_listenCts.IsCancellationRequested)//true
            //    {
            //        if (!ValveInHot_State)
            //        {
            //            AddCompose("处理泄漏异常：关闭蒸汽阀");
            //            break;
            //        }
            //        Thread.Sleep(_sleepfast);
            //    }
            //}, () =>
            //{
            //    while (!_listenCts.IsCancellationRequested)//true
            //    {
            //        if (!ValveIsobutene_State)
            //        {
            //            AddCompose("处理泄漏异常：关闭异丁烯进料阀");
            //            break;
            //        }
            //        Thread.Sleep(_sleepfast);
            //    }
            //});

            StopWarning(WarningType.泄漏);
            _warningDicionary[WarningType.泄漏] = true;
        }

        #endregion

        #endregion

        #region  重写公共方法
        bool _isbeginned = false;
        public override void Begin()
        {
            ListenOPCRelation();
            _isbeginned = true;
        }
        public override async Task<string> CheckDefault()
        {
            StringBuilder builder = new StringBuilder();
            await InitServerData();
            if (_details == null )
                builder.AppendLine("可能由于网络原因，导致获取数据失败，请点击\"确定\"按钮 尝试重新获取");

            return builder.ToString();
        }

        public override void Over()
        {
            this._listenCts.Cancel();
            CalcFlowAndStep();
            Score = CalcScore();
            //CloseAllRelay();
            Finish();
        }

        //步骤 标识
        bool _isCanopenAmmonia = false;
         private void ListenOPCRelation()
        {
            var volume_ben = 0d;
            var volume_ammonia = 0d;
            var volume_oxygen = 0d;
            ThreadPool.QueueUserWorkItem((o) =>
            {
       
                #region  闸阀正常开车前状态为开
                Task.Run(() =>
                    {
                        while (!_listenCts.IsCancellationRequested)
                        {
                            if (ValveGate1_State)
                            {
                                if (Isinner) ValveGate1_item.Open();
                                FlowInBox_item.StartFlow();
                            }
                            else
                            {
                                if (!Isinner) ValveGate1_item.Close();
                                FlowInBox_item.StopFlow();
                            }
                        }
                    });
                #endregion

                #region 风机系统

                #region  开启罗茨风机
                Task.Run(() =>
                    {
                        while (!_listenCts.IsCancellationRequested)
                        {
                            //此处流量在300-600m3/h范围
                            if (_valveFanState)
                            {
                                if (!Isinner)
                                    ValveInO2_item.Open();
                                FlowInO2_item.StartFlow();
                                if (_flow_oxygen_value < 300)
                                {
                                    _flow_oxygen_increment = 20;
                                }
                                else if (_flow_oxygen_value >= 600)
                                {
                                    _flow_oxygen_increment = 0;
                                }
                                else
                                {
                                    _flow_oxygen_increment = 2;
                                }

                                if (_flow_oxygen_value < 650)
                                {
                                    _flow_oxygen_value += _flow_oxygen_increment;
                                    LabelFlowO2_item.Write(_flow_oxygen_value);
                                }
                            }
                            else
                            {
                                if (!Isinner)
                                {
                                    ValveInO2_item.Close();
                                }
                                FlowInO2_item.StopFlow();

                                _flow_oxygen_value -= _flow_oxygen_decrement;
                                if (_flow_oxygen_value <= 0)
                                    _flow_oxygen_value = 0;
                                LabelFlowO2_item.Write(_flow_oxygen_value);
                            }

                            Thread.Sleep(_sleepfast);
                        }
                    }
                    );
                #endregion

                #region 空气进去电加热器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (ValveInEleHeater_State)
                        {
                            if (!Isinner)
                                ValveInEleHeater_item.Open();
                            //2段flow分开
                            FlowInElcHt_item.StartFlow();
                            FlowOutO2_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                ValveInEleHeater_item.Close();
                            FlowInElcHt_item.StopFlow();
                            if(!ValveO2Reactor_State)
                                FlowOutO2_item.StopFlow();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 空气直接进入流化床反应器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (ValveO2Reactor_State)
                        {
                            if (!Isinner)
                                ValveOutEleHeater_Item.Open();
                            FlowO2Rec_item.StartFlow();
                            FlowOutO2_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                ValveOutEleHeater_Item.Close();
                            FlowO2Rec_item.StopFlow();
                            if (!ValveInEleHeater_State)
                            FlowOutO2_item.StopFlow();
                        }
                    }
                });
                #endregion

                #region 电加热器进入流化床反应器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (ValveOutEleHeater_State)
                        {
                            if (!Isinner)
                                ValveOutEleHeater_Item.Open();
                            FlowOutElcHt_item.StartFlow();
                        }
                        else
                        {
                            if (!Isinner)
                                ValveOutEleHeater_Item.Close();
                            FlowOutElcHt_item.StopFlow();
                        }
                    }
                });
                #endregion

                #region  电加热器进入流化床反应器 - 温度变化+

                Task.Run(() =>
                    {
                        while (!_listenCts.IsCancellationRequested)
                        {
                            if (ValveInO2_State && ValveInEleHeater_State && ValveOutEleHeater_State)
                            {
                                //空气进入规定温度
                                if (_valveElectricHeaterState)
                                    _temperature1_increment = _temperature1_value < 300 ? 3 : 1;
                                else
                                    _temperature1_increment = 0;
                                //开油泵 200度以上
                                if (_temperature1_value > 200)
                                    _temperature1_increment = ValveOilPump_State ? 3 : 0;

                                if (_temperature1_value >= 360)
                                {
                                    _temperature1_increment = 0;
                                    _isCanopenAmmonia = true;
                                }
                                _temperature1_value += _temperature1_increment;
                                LabelTemperature1_item.Write(_temperature1_value);
                            }
                            else
                            {
                                //降温 混合气关闭  ,自然降温
                                if (!ValveAmmoniaBenzene_State && _temperature1_value>100)
                                {
                                    _temperature1_decrement = _temperature1_value < 22 ? 0 : 1;
                                    _temperature1_value -= _temperature1_decrement;
                                    LabelTemperature1_item.Write(_temperature1_value);
                                }
                            }

                            Thread.Sleep(_sleepfast);
                        }
                    });
                #endregion 

                #region 吹空气，自然降温
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (ValveInO2_State && ValveO2Reactor_State)
                        {
                            _temperature1_decrement = _temperature1_value < 60 ? 1 : 3;
                            _temperature1_decrement = _temperature1_value < 22 ? 0 : _temperature1_decrement;
                            _temperature1_value -= _temperature1_decrement;
                            LabelTemperature1_item.Write(_temperature1_value);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion 
                #endregion

                #region 氨气系统
                #region  液氨汽化 - 流量变化 -
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_inputAmmoniaState > 0)
                        {
                            FlowInAmmonia_item.StartFlow();
                            var flow = _inputAmmoniaState*10;

                            if (flow > _flow_ammonia_value)
                            {
                                _flow_ammonia_value += 1;
                            }
                            else if (flow < _flow_ammonia_value)
                            {
                                _flow_ammonia_value -= 1;
                            }
                        }
                        else
                        {
                            FlowInAmmonia_item.Close();
                            _flow_ammonia_value = 0;
                            
                        }

                        LabelFlowAmmonia_item.Write(_flow_ammonia_value);
                        Thread.Sleep(_sleepfast);
                    }
                }
                    );


                #endregion

                #region  氨气进料 - 压力变化
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_inputAmmoniaState>0 && ValveAmmoniaBufTank_State)
                        {
                            if (!Isinner) ValveAmmoniaBufTank_item.Open();
                            FlowOutAmmonia_item.StartFlow();
                            //规定压力[0.2-0.4]  //实际压力[0.1-0.5]
                            _pressure_ammonia_increment = _pressure_ammonia_value < 0.4 ? 0.01:0;

                            _pressure_ammonia_value += _pressure_ammonia_increment;
                            LabelAmmoniaPressure_item.Write(_pressure_ammonia_value);
                        }
                        else
                        {
                            if (!Isinner)
                            {
                                ValveInAmmonia_item.Close();
                                ValveAmmoniaBufTank_item.Close();
                            }
                            FlowOutAmmonia_item.Close();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                }
                    );


                #endregion

                #endregion

                #region  间二甲苯进料 - 流量变化
                Task.Run(() =>
                    {
                        while (!_listenCts.IsCancellationRequested)
                        {
                            if (_inputBenState > 0)
                            {
                                FlowInBen_item.StartFlow();
                                var flow = _inputBenState*30;
                                if (flow > _flow_benzene_value)
                                    _flow_benzene_value +=10;
                                else if (flow < _flow_benzene_value)
                                    _flow_benzene_value -= 10;
                            }
                            else
                            {
                                FlowInBen_item.StopFlow();
                                _flow_benzene_value = 0;
                            }
                            LabelFlowBenlene_item.Write(_flow_benzene_value);

                            Thread.Sleep(_sleepfast);
                        }

                    });
                 
                #endregion

                #region 间二甲苯 与 氨气 混合 放入流化床反应器 温度+
                Task .Run(()=>
                    {
                        while(!_listenCts.IsCancellationRequested)
                        {
                            if (ValveAmmoniaBenzene_State)
                            {
                                if (!Isinner)
                                    ValveAmmoniaBenzene_item.Open();
                                FlowOutAmmoniaBen_item.StartFlow();

                                //if ( ValveInAmmonia_State && ValveAmmoniaBufTank_State)
                                if (_inputAmmoniaState>0 && ValveAmmoniaBufTank_State)
                                {
                                    //加二甲苯进料规定温度[380-430]  实际温度[380-460]
                                    //_temperature1_increment = _temperature1_value < 380 ? 0.5 : 0.25;
                                    _temperature1_increment = _temperature1_value < 380 ? 2 : 1;
                                    //开油泵 200度以上
                                    if (_temperature1_value > 200)
                                        _temperature1_increment = ValveOilPump_State ? _temperature1_increment : 0;

                                    if(_temperature1_value>460)
                                        _temperature1_increment = 0;
                                    _temperature1_value += _temperature1_increment;
                                    LabelTemperature1_item.Write(_temperature1_value);
                                }
                            }
                            else
                            {
                                if(!Isinner)
                                    ValveAmmoniaBenzene_item.Close();
                                FlowOutAmmoniaBen_item.StopFlow();
                            }
                            Thread.Sleep(_sleepfast);
                        }
                    });



                #endregion

                #region 计算比例 
                Task.Run(() =>
                {                 
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_inputBenState > 0 && _inputAmmoniaState > 0 && ValveAmmoniaBufTank_State)
                        {
                            //var rate = volume_ammonia / volume_ben;
                            if (_flow_benzene_value > 0)
                            {
                                var rate = _flow_ammonia_value/(_flow_benzene_value/9);
                                _rate_ammoniaBenzene_value = Math.Round(rate, 2);
                                LabelAmmoniaBenRateRate_item.Write(_rate_ammoniaBenzene_value);
                            }
                        }

                        //if (_inputBenState > 0 && _inputAmmoniaState > 0 && ValveInO2_State)
                        if (_inputBenState > 0 && _inputAmmoniaState > 0 && _flow_oxygen_value>0)
                        {
                            if (_flow_benzene_value > 0)
                            {
                                var rate = _flow_oxygen_value/(_flow_benzene_value/7);
                                _rate_gasBenzene_value = Math.Round(rate, 2);
                                LabelGasBenRate_item.Write(_rate_gasBenzene_value);
                            }
                        }

                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion


                #region 软水进水，降温.阀
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInWaterState)
                        {
                            if (!Isinner)
                            {
                                ValveInWater_item.Open();
                            }
                            FlowInSoftWater_item.StartFlow();
                            _temperature1_value = Math.Round(_temperature1_value, 2);
                            //软水进规定温度[390-425]  实际温度[380-430]
                            
                            //_temperature1_decrement = _temperature1_value < 380 ? 5 : 8;
                            //_temperature1_decrement = _temperature1_value < 22 ? 0 : _temperature1_decrement;
                            _temperature1_decrement = _temperature1_value < 22 ? 0 : 2;
                            _temperature1_value -= _temperature1_decrement;                          
                            LabelTemperature1_item.Write(_temperature1_value);
                        }
                        else
                        {
                            if (!Isinner)
                            {
                                ValveInWater_item.Close();
                            }
                            FlowInSoftWater_item.Close();
                            LabelTemperature1_item.Write(_temperature1_value);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                
            });
        }
        private void  CalcFlowAndStep()
        {
            #region 计算流程
            //1.正常开车步骤
        
            //1.1 计算空气流量
          
            var avg_flowO2_count = _steps.Count(i => i.Status[StatusName.罗茨风机开关] == open);
            var avg_flowO2 = avg_flowO2_count > 0 ? _steps.Where(i => i.Status[StatusName.罗茨风机开关] == open).Average(i => i.Status[StatusName.空气流量]) : -1;
 
            //外循环打开的item
            var first_loopopen_item = _steps.FirstOrDefault(i => i.Status[StatusName.导热油循环泵] == open );

            //1.2 氨气流量
            var avg_flowammonia_count = _steps.Count(i=>i.Status[StatusName.氨气阀门]>0&&i.Status[StatusName.氨气流入缓冲罐阀门]==open);
            var avg_flowammonia = avg_flowammonia_count > 0 ?
                _steps.Where(i => i.Status[StatusName.氨气阀门] >0 && i.Status[StatusName.氨气流入缓冲罐阀门] == open).Average(i => i.Status[StatusName.氨气流量]) : -1;
            //1.2.1首次打开氨气阀门的item
            var first_ammoniaopen_item = _steps.FirstOrDefault(i => i.Status[StatusName.氨气阀门] >0);

            //1.3 氨气压力
            var nitrogenpressure_count = _steps.Count(i => i.Status[StatusName.氨气阀门] >0 && i.Status[StatusName.氨气流入缓冲罐阀门] == open);
            var nitrogenpressure = nitrogenpressure_count > 0 ? _steps.Where(i => i.Status[StatusName.氨气阀门] >0 && i.Status[StatusName.氨气流入缓冲罐阀门] == open).Average(i => i.Status[StatusName.氨缓冲罐压力]) : -1;

            //1.4 间二甲苯流量
            var first_benopen_item = _steps.FirstOrDefault(i => i.Status[StatusName.间二甲苯进料阀] >0);
            var flowxylene_count = _steps.Count(i => i.Status[StatusName.间二甲苯进料阀] > 0);
            var flowxylene = flowxylene_count > 0 ? _steps.Where(i => i.Status[StatusName.间二甲苯进料阀] > 0).Average(i => i.Status[StatusName.间二甲苯流量]) : -1;
            //1.5 氨气：苯          
            var rate1_count = _steps.Count(i => i.Status[StatusName.间二甲苯进料阀] > 0 && i.Status[StatusName.间二甲苯流入反应器阀门] == open && i.Status[StatusName.氨气阀门] > 0 &&
                i.Status[StatusName.氨气流入缓冲罐阀门]==open);
            var rate1 = rate1_count > 0 ? _steps.Where(i => i.Status[StatusName.间二甲苯进料阀] > 0 && i.Status[StatusName.间二甲苯流入反应器阀门] == open && i.Status[StatusName.氨气阀门] > 0 &&
                i.Status[StatusName.氨气流入缓冲罐阀门] == open).Average(i => i.Status[StatusName.氨气与间二甲苯比例]) : -1;

           //1.6 空气与苯比例
            //var rate2_count = _steps.Count(i=>i.Status[StatusName.空气阀门]==open &&i.Status[StatusName.空气流入电加热器阀门]==open &&i.Status[StatusName.空气流出电加热器]==open
            //    && i.Status[StatusName.间二甲苯进料阀]==open&& i.Status[StatusName.间二甲苯流入反应器阀门]==open);
            //var rate2 = rate2_count > 0 ? _steps.Where(i => i.Status[StatusName.空气阀门] == open && i.Status[StatusName.空气流入电加热器阀门] == open && i.Status[StatusName.空气流出电加热器] == open
            //    && i.Status[StatusName.间二甲苯进料阀] == open && i.Status[StatusName.间二甲苯流入反应器阀门] == open).Average(i => i.Status[StatusName.空气与间二甲苯比例]) : -1;
            var rate2_count = _steps.Count(i => i.Status[StatusName.罗茨风机开关] == open && i.Status[StatusName.间二甲苯进料阀] > 0 && i.Status[StatusName.间二甲苯流入反应器阀门] == open);
            var rate2 = rate2_count > 0 ? _steps.Where(i => i.Status[StatusName.罗茨风机开关] == open && i.Status[StatusName.间二甲苯进料阀] > 0 && i.Status[StatusName.间二甲苯流入反应器阀门] == open).Average(i => i.Status[StatusName.空气与间二甲苯比例]) : -1;
          
            //1.7 软水进，浓1处降温
         
            var temp1_count = _steps.Count(i => i.Status[StatusName.冷却水进水阀] == open);
            var temp1 = temp1_count > 0 ? _steps.Where(i => i.Status[StatusName.冷却水进水阀] == open ).Average(i => i.Status[StatusName.浓1温度]) : -1;
         
            //1.8平均温度,  计算>390
            var avg_temperature_items = _steps.Where(i => i.Status[StatusName.浓1温度] > 390);


            //2停车步骤：
            //2.1 关闭间二甲苯进料相关阀门
            var benlene_latestopen_item = _steps.Where(i => i.Status[StatusName.间二甲苯进料阀] > 0).OrderByDescending(i => i.Date).FirstOrDefault();
            var benlene_close_item = benlene_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.间二甲苯进料阀] == 0 && i.Date >
                benlene_latestopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;
            // 2.2  关闭氨气进料阀门
            var nitrogen_latestopen_item = _steps.Where(i => i.Status[StatusName.氨气阀门] >0).OrderByDescending(i => i.Date).FirstOrDefault();
            var ammonia_close_item = nitrogen_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.氨气阀门] == 0 && i.Date >
                nitrogen_latestopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;
            //2.3 关闭混合阀门
            var ammoniaben_lastopen_item = _steps.Where(i => i.Status[StatusName.间二甲苯流入反应器阀门] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            var ammoniaben_close_item = ammoniaben_lastopen_item != null ? _steps.Where(i => i.Status[StatusName.间二甲苯流入反应器阀门] == close && i.Date > ammoniaben_lastopen_item.Date)
                .OrderBy(i => i.Date).FirstOrDefault() : null;
           

            var mixed_lateestopen_item = _steps.Where(i => i.Status[StatusName.间二甲苯流入反应器阀门] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            var mixed_close_item = mixed_lateestopen_item != null ? _steps.Where(i => i.Status[StatusName.间二甲苯流入反应器阀门] == close).OrderBy(i => i.Date).FirstOrDefault() : null;


            var softwater_latesteopen_item = _steps.Where(i => i.Status[StatusName.经热水泵进水阀门] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            var softwater_close_item = softwater_latesteopen_item != null ? _steps.Where(i => i.Status[StatusName.经热水泵进水阀门] == close &&
                i.Date > softwater_latesteopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;

            // 2.3 降温到60C以下
            //var temp2_count = _steps.Count(i=>i.Status[StatusName.空气阀门]==open && i.Status[StatusName.空气流入反应器阀门]==open);
            //var temp2 = temp2_count > 0 ? _steps.Where(i => i.Status[StatusName.空气阀门] == open && i.Status[StatusName.空气流入反应器阀门] == open).Average(i => i.Status[StatusName.浓1温度]) : -1;
            var o2react_latestopen_item = _steps.Where(i => i.Status[StatusName.空气流入反应器阀门] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            var o2react_close_item = o2react_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.空气流入反应器阀门]==close && i.Date > o2react_latestopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;
            var temp2_item = o2react_close_item != null ? _steps.Where(i => i.Status[StatusName.空气阀门] == open  && i.Date > o2react_close_item.Date 
                ).OrderByDescending(i => i.Status[StatusName.浓1温度]).ThenByDescending(i => i.Date).FirstOrDefault():null;
         
           // 2.4 关闭空气阀门
            var O2_latestopen_item = _steps.Where(i => i.Status[StatusName.罗茨风机开关] == open).OrderByDescending(i => i.Date).FirstOrDefault();
            var O2_close_item = O2_latestopen_item != null ? _steps.Where(i => i.Status[StatusName.罗茨风机开关] == close
                &&i.Date>O2_latestopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;


            #endregion

            #region  计算分数
            #region 1.开启罗茨风机，空气流量
            if (avg_flowO2 != -1)
            {
                if (avg_flowO2 < 300)
                {
                    AddCompose("充空气：流量值小于300 m3/h");
                }
                else if (avg_flowO2 >= 300 && avg_flowO2 <= 600)
                {
                    AddCompose("充空气：流量在正常范围300-600 m3/h");
                }
                else
                {
                    AddCompose("充空气：流量值超过600 m3/h");
                }
            } 
            #endregion

            #region 2.开外循环泵
            if (first_loopopen_item != null)
            {
                var temperature_loop = first_loopopen_item.Status[StatusName.浓1温度];
                if (temperature_loop >= 170 && temperature_loop <= 200)
                     AddCompose("打开导热油循环泵");
                else if (temperature_loop < 170)
                    AddCompose("打开导热油循环泵过早");
                else
                    AddCompose("打开导热油循环泵过晚");
            } 
            #endregion

            #region 3.通入氨气
            //3.1 氨气阀门打开时间
            if (first_ammoniaopen_item != null)
            {
                var temperature_ammonia = first_ammoniaopen_item.Status[StatusName.浓1温度];
                if (_isCanopenAmmonia)
                {
                    if (temperature_ammonia <= 350)
                        AddCompose("锥底温度降至350℃，打开氨气阀");
                    else
                        AddCompose("锥底温度高于350℃，打开氨气阀");
                }
                else
                {
                    AddCompose("锥底温度未到达360℃，过早打开氨气阀");
                }
            }

            //3.2 氨气流量
            if (avg_flowammonia != -1)
            {
                if (avg_flowammonia < 20)
                {
                    AddCompose("氨气进料：流量值小于20 m3/h");
                }
                else if (avg_flowammonia >= 20 && avg_flowammonia <= 80)
                {
                    AddCompose("氨气进料：流量在正常范围20-80m3/h");
                }
                else
                {
                    AddCompose("氨气进料：流量值超过80m3/h");
                }
            }
            //3.3 氨气缓冲罐的压力 
            if (nitrogenpressure != -1)
            {
                if (nitrogenpressure < 0.2)
                {
                    AddCompose("氨气缓冲罐压力：压力低压0.2MPa");
                }
                else if (nitrogenpressure >= 0.2 && nitrogenpressure <= 0.4)
                {
                    AddCompose("氨气缓冲罐压力：压力在正常范围0.2-0.4Mpa");
                }
                else
                {
                    AddCompose("氨气缓冲罐压力：压力高于0.4MPa");
                }
            } 
            #endregion

            #region 4.通入间二甲苯
            //4.1打开间二甲苯进料阀
            if (first_benopen_item != null)
            {
                var temperature_ben = first_benopen_item.Status[StatusName.浓1温度];
                if (temperature_ben >= 380)
                    AddCompose("锥底温度达380℃，打开间二甲苯进料阀");
                else
                    AddCompose("锥底温度未达380℃，打开间二甲苯进料阀");
            }
            //4.2间二甲苯进料时，流量的检测
            if (flowxylene != -1)
            {
                if (flowxylene < 60)
                    AddCompose("间二甲苯进料:流量小于60L/h");
                else if (flowxylene >= 60 && flowxylene <= 120)
                    AddCompose("间二甲苯进料：流量在正常范围60-120L/h");
                else
                    AddCompose("间二甲苯进料:流量大于120L/h");
            }

            //4.3氨气与间二甲苯混合气体进入，氨气与间二甲苯比例
            if (rate1 != -1)
            {
                if (rate1 < 5)
                    AddCompose("氨气与间二甲苯比例小于5 mol%");
                else if (rate1 >= 5 && rate1 <= 7)
                    AddCompose("氨气与间二甲苯比例正常范围5-7 mol%");
                else
                    AddCompose("氨气与间二甲苯比例大于7 mol%");
            }


            //4.4空气与间二甲苯比例
            if (rate2 != -1)
            {
                if (rate2 < 35)
                    AddCompose("空气与间二甲苯比例小于35 v%");
                else if (rate2 >= 35 && rate2 <= 40)
                    AddCompose("空气与间二甲苯比例在正常范围35-40 v%");
                else
                    AddCompose("空气与间二甲苯比例大于40 v%");
            } 
            #endregion
            bool isreactionover = false;

            #region 5.反应温度[390-425] 和 反应时间
            if (avg_temperature_items.Any())
            {
                var avg_temperature = avg_temperature_items.Average(i => i.Status[StatusName.浓1温度]);
                if (avg_temperature >= 390 && avg_temperature <= 425)
                {
                    AddCompose("反应温度：浓1处温度在正常范围390-425℃");
                }
                else if (avg_temperature < 390)
                {
                    AddCompose("反应温度：浓1处温度低于390℃");
                }
                else
                {
                    AddCompose("反应温度：浓1处温度高于425℃");
                }


                var avg_temperature_count = avg_temperature_items.Count();
                var reaction_total_second = avg_temperature_count / 2;
                if (reaction_total_second > _reactionSecond)
                {
                    AddCompose("反应时间正常");
                    isreactionover = true;
                }
                else
                {
                    AddCompose("反正时间不足");
                }
            } 
            #endregion



           
            #region 6.停车
            //6.1 停止通间二甲苯 ， 停止通氨，混合阀门
            if (benlene_close_item != null && ammonia_close_item != null)
            {
                if (isreactionover)
                {
                    if (benlene_close_item.Date < ammonia_close_item.Date)
                    {
                        AddCompose("停车：关闭间二甲苯进料阀门");
                        AddCompose("停车：关闭氨气阀门");
                    }
                    else
                    {
                        AddCompose("停车：关闭氨气阀门早于关闭间二甲苯阀门");
                    }
                    if (ammoniaben_close_item != null)
                    {
                        if (ammoniaben_close_item.Date > benlene_close_item.Date)
                            AddCompose("停车：关闭混合器阀门");
                        else
                            AddCompose("停车：关闭混合器阀门早于关闭间二甲苯阀门");
                    }
                    //else
                    //    AddCompose("停车：未关闭混合器阀门");
                }
                else
                {
                    AddCompose("停车：反应未完成，过早关闭间二甲苯阀门和氨气阀门");
                }
            } 
            #endregion

            #region 7.降温
            if (temp2_item != null)
            {
                var temp2 = temp2_item.Status[StatusName.浓1温度];
                if (temp2 < 60)
                {
                    AddCompose("锥底降到正常温度60℃下");
                }
            }
            if (ammonia_close_item != null && O2_close_item != null)
            {
                if (ammonia_close_item.Date < O2_close_item.Date)
                {
                    AddCompose("停车：空气进料阀门关闭");
                }
            } 
            #endregion
            #endregion
        }
        #endregion

        #region  写串口数据

        #endregion

        #region  操作继电器
        /// <summary>
        /// 开始泄漏
        /// </summary>
        void BeginLeak()
        {
            FlashWarning_item.Open();
            //_relay_command = _relay_command | _fognumber;
            //SPWriteTool(_relay_command);
            Thread.Sleep(500);
            StopLeak();

        }
        /// <summary>
        /// 停止泄漏
        /// </summary>
        void StopLeak()
        {
            FlashWarning_item.Close();
            //_relay_command = _relay_command & (~_fognumber);
            //SPWriteTool(_relay_command);
        }
        void BeginWarning(WarningType type)
        {
            if (!_warningtypes.Contains(type))
            {
                FlashWarning_item.Open();
                _warningtypes.Add(type);
                //_relay_command = _relay_command | _warning1number;//响
                //_relay_command = _relay_command | _warning2number;//亮
                //SPWriteTool(_relay_command);
            }
        }

        void StopWarning(WarningType type)
        {
            if (_warningtypes.Contains(type))
            {
                FlashWarning_item.Close();
                //_relay_command = (~_warning1number) & _relay_command;
                //_relay_command = (~_warning2number) & _relay_command;
                //SPWriteTool(_relay_command);
                _warningtypes.Remove(type);
            }
        }
        #endregion

        #region 枚举定义
        enum FiledName
        {
            //开关
            ValveC8H10, ValveC8H10Bottom, ValveC8H10Top, ValveAmmoniaBenzene, ValveInNH3, ValveNH3BufTank, ValveNH3Bottom, ValveNH3Top, ValveInO2,
            ValveO2AirHeater, ValveO2Reactor, ValveInEleHeater, ValveOutEleHeater, ValveInOil, ValveOutOil, ValveOilRight, ValveOilLeft, ValveOutAirHeater,
            ValveInCold, ValveOutCold, ValveOilPump, ValveHotPump, ValveInHotPump, ValveColdBottom, ValveColdTop, ValveH2ORec, ValveGate1, ValveGate2,
            ValveCutOff,


            //管道
            FlowInCold, FlowOutCold, FlowInSoftWater, FlowOutOil, FlowInC8H10, FlowOutAmmoniaBen, FlowInO2, FlowOilInnerLoop, FlowOilNH3Ht,
            FlowOilC8H10Ht, FlowOutAirHt, FlowO2Rec, FlowOutO2, FlowOutElcHt, FlowOutCold1, FlowPumpOil, FlowInBox,

            //标签
            LabelFlowNH3, LabelFlowO2, LabelTemperature1, LabelTemperature2, LabelTempNH3,
            LabelTempOil,
            //闪烁
            FlashTemperature1, FlashTemperature2,
            FlashAmmoniaFlow,
            FlashBenFlow,
            FlashGasFlow,
            FlashAmmoniaBenRate,
            FlashGasBenRate,
            FlashEletricTemperature,
            FlashAmmoniaPressure,

            LabelAmmoniaBenRateRate,
            LabelFlowBenlene,
            LabelAmmoniaPressure,
            LabelEletricTemperature,
            LabelGasBenRate,
            FlowOutAmmonia,
            FlowInAmmonia,
            FlowInElcHt,
            InputBen,
            InputAmmonia,
            ValveFan,
            ValveElectricHeater,
            ValveInWater,
            FlashWarning
        }
        enum StatusName
        {
            间二甲苯流量, 氨气流量, 空气流量, 氨缓冲罐压力, 浓1温度, 浓2温度, 氨气与间二甲苯比例, 空气与间二甲苯比例, 间二甲苯进料阀,
            间二甲苯流入反应器阀门, 氨气阀门, 氨气流入缓冲罐阀门,
            空气阀门, 空气流入空气加热器阀门, 空气流入反应器阀门, 空气流入电加热器阀门, 空气流出电加热器, 外循环进油阀门, 出油阀门, 右侧出油阀门, 左侧出油阀门,
            经空气加热器出油阀门, 冷却水上水阀门, 冷却水回水阀门, 经热水泵进水阀门,
            软水流入反应器阀门, 闸阀1, 闸阀2, 导热油循环泵,
            热水泵阀门,
            液氨进料调节阀,
            间二甲苯进料调节阀,
            罗茨风机开关,
            电加热器开关,
            冷却水进水阀
        }

        private enum WarningType
        {
            温度异常,
            泄漏
        }

        #endregion
    }
}
